﻿using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Presentation.Commands;
using Refract.Navigation;
using System.Collections;

namespace Refract.Demo.Infrastructure
{
    public partial class Menu : UserControl
    {
        public Menu()
        {
            InitializeComponent();
        }
        public static readonly DependencyProperty PagesProperty =
            DependencyProperty.Register("Pages", typeof(PageItemList),
            typeof(Menu), new PropertyMetadata(Menu.OnPagesChanged));
        
        public PageItemList Pages
        {
            get { return (PageItemList)GetValue(PagesProperty); }
            set { SetValue(PagesProperty, value); }
        }

        protected static void OnPagesChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            Menu menu = obj as Menu;
            menu.SetPages();
        }

        private void SetPages()
        {
            Pages.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Pages_CollectionChanged);
        }

        void Pages_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    Build(e.NewItems);
                    break;
                case NotifyCollectionChangedAction.Remove:
                    Build();
                    break;
                case NotifyCollectionChangedAction.Replace:
                    Build();
                    break;
                case NotifyCollectionChangedAction.Reset:
                    Build();
                    break;
                default:
                    break;
            }            
        }

        /// <summary>
        /// Builds the specified page list.
        /// </summary>
        /// <param name="pageList">The page list.</param>
        private void Build(IEnumerable pageList)
        {
            foreach (PageItem page in pageList)
            {
                Button button = new Button() { Content = new TextBlock() { Text = page.Name } };
                Click.SetCommand(button, page.Command);
                Click.SetCommandParameter(button, page.Name);
                LayoutRoot.Children.Add(button);
            }
        }
        
        protected void Build()
        {
            
            LayoutRoot.Children.Clear();

            Build(Pages);
            
        }
    }
}
